package com.xrit.sunnyday.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.constant.RedisMessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Member;
import com.xrit.sunnyday.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 手机登录 注册
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @PostMapping("/check")
    public Result checkMember(@RequestBody Map<String,String> loginInfo, HttpServletResponse res){
        //1.从redis连接池获取链接
        Jedis jedis = jedisPool.getResource();
        //2.取出用户传过来的手机号
        String telephone = loginInfo.get("telephone");
        //验证码的key
        String key = RedisMessageConstant.SENDTYPE_LOGIN + "_" + telephone;
        //3.获取redis中的验证码,key对应的value
        String codeInRedis = jedis.get(key);
        //4.判断验证码是否存在
        if (StringUtils.isEmpty(codeInRedis)){
            //6.没有值就重新发送
            return new Result(false,"请重新获取验证码!");
        }
        String validateCode = loginInfo.get("validateCode");
        if (!codeInRedis.equals(validateCode)){
            //不匹配反回
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        jedis.close();
        //7.通手机号判断是否是会员
        Member member = memberService.findByTelephone(telephone);
        if (null == member) {
            //不是会员：填充会员信息
            member = new Member();
            //注册时间
            member.setRegTime(new Date());
            //注册手机号码
            member.setPhoneNumber(telephone);
            //标记
            member.setRemark("手机快速注册");
            //添加为新会员
            memberService.add(member);
        }
        //8.是会员
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        //存一个月
        cookie.setMaxAge(30*24*60*60);
        //访问的路径,根路径下时网站的所有路径都会发送cookie
        cookie.setPath("/");
        res.addCookie(cookie);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }


}
